import * as Y from 'yjs';
import { WebsocketProvider } from 'y-websocket';
import { v4 as uuidv4 } from 'uuid';
import { fabric } from 'fabric';
// 创建一个协作包装器
export function setupCollaboration(canvas, roomId, userName, undoRedoManagerRef) {
    console.log('Setting up collaboration with undoRedoManagerRef:', undoRedoManagerRef);
    console.log(`设置协作: 房间ID=${roomId}`);

    // 初始化Yjs文档
    const ydoc = new Y.Doc();

    // 使用共享Map而不是Array，这样更容易跟踪和更新对象
    const sharedObjects = ydoc.getMap('canvas-objects');

    // 创建WebSocket连接
    console.log('正在创建WebSocket连接...');
    console.log('连接URL:', 'ws://localhost:9879');
    console.log('房间ID:', roomId);

    const wsProvider = new WebsocketProvider('ws://localhost:9879', roomId, ydoc, {
        connect: true,
        WebSocketPolyfill: WebSocket
    });

    // 获取awareness
    const awareness = wsProvider.awareness;

    // 保存用户ID
    const userId = uuidv4().substring(0, 8);
    console.log(`用户ID: ${userId}`);

    // 防止重复更新的变量
    let isUpdatingFromRemote = false;

    // 添加变量用于跟踪最后一次处理的清空画布事件时间戳
    let lastClearCanvasTime = 0;

    // 添加变量用于跟踪最后处理的命令
    let lastProcessedCommand = null;

    // 监听连接状态
    wsProvider.on('status', (status) => {
        // console.log(`协同状态变更: ${status}, 时间: ${new Date().toLocaleTimeString()}`);
        // console.log('WebSocket连接状态:', wsProvider.wsconnected ? '已连接' : '未连接');
    });

    // 检查连接是否已建立的辅助函数
    const checkConnection = () => {
        const isConnected = wsProvider.wsconnected;
        // console.log(`连接状态检查: ${isConnected ? '已连接' : '未连接'}`);

        // 手动触发自定义事件
        const event = new CustomEvent('collaboration-status-changed', {
            detail: { status: isConnected ? 'connected' : 'disconnected' }
        });
        document.dispatchEvent(event);

        return isConnected;
    };

    // 立即检查一次连接状态
    setTimeout(checkConnection, 1000);

    // 添加连接和断开事件监听
    wsProvider.on('connection-close', () => {
        // console.log('WebSocket连接已关闭');
        checkConnection();
    });

    wsProvider.on('connection-error', (error) => {
        console.error('WebSocket连接错误:', error);
        checkConnection();
    });

    wsProvider.on('connection-open', () => {
        // console.log('WebSocket连接已打开');
        checkConnection();

        // 连接建立后，请求当前状态
        console.log('同步画布状态...');

        // 清除当前画布
        if (canvas) {
            canvas.clear();
        }

        // 同步共享地图中的所有对象
        updateCanvasFromSharedObjects();
    });

    // 设置用户信息
    awareness.setLocalStateField('user', {
        name: userName,
        color: getRandomColor(),
        userId: userId
    });

    // 监听自定义消息事件
    wsProvider.on('custom-event', (event) => {
        console.log('接收到自定义事件:', event);

        // 处理清空画布事件
        if (event && event.type === 'clear-canvas') {
            console.log('收到清空画布指令，执行本地清空操作');
            if (canvas) {
                isUpdatingFromRemote = true; // 阻止触发同步操作
                canvas.clear();
                canvas.setBackgroundColor('#ffffff', canvas.requestRenderAll.bind(canvas));

                // 延迟恢复标志
                setTimeout(() => {
                    isUpdatingFromRemote = false;
                }, 100);

                // 触发本地清空画布事件
                const clearEvent = new CustomEvent('canvas-cleared-remotely');
                document.dispatchEvent(clearEvent);
            }
        } else if (event && event.type === 'delete-object') {
            console.log('收到删除对象事件:', event.objectId);

            isUpdatingFromRemote = true;

            // 查找并删除对象
            const objectToDelete = findObjectById(canvas, event.objectId);
            if (objectToDelete) {
                console.log('从画布删除远程对象:', event.objectId);
                canvas.remove(objectToDelete);
                canvas.requestRenderAll();
            }

            // 从共享对象中移除
            if (sharedObjects.has(event.objectId)) {
                sharedObjects.delete(event.objectId);
            }

            setTimeout(() => {
                isUpdatingFromRemote = false;
            }, 100);
        }
    });

    const broadcastClearCanvas = () => {
        if (!wsProvider.wsconnected) {
            console.warn('WebSocket未连接，无法广播清空画布事件');
            return false;
        }

        try {
            console.log('广播清空画布事件');

            // 清空所有共享对象（保留光标对象）
            const objectsToDelete = [];
            sharedObjects.forEach((_, key) => {
                if (!key.includes('cursor')) {
                    objectsToDelete.push(key);
                }
            });

            // 删除所有非光标对象
            objectsToDelete.forEach(key => {
                sharedObjects.delete(key);
            });

            // 创建一个包含唯一时间戳的清空事件
            const clearTimestamp = Date.now();
            console.log('发送清空画布事件，时间戳:', clearTimestamp);

            // 使用awareness机制发送清空消息
            wsProvider.awareness.setLocalStateField('clearCanvas', {
                action: 'clear',
                userId: userId,
                timestamp: clearTimestamp
            });

            // 短暂延迟后清除通知，避免状态污染
            setTimeout(() => {
                wsProvider.awareness.setLocalStateField('clearCanvas', null);
            }, 500);

            return true;
        } catch (error) {
            console.error('广播清空画布事件失败:', error);
            return false;
        }
    };

    // 广播撤销/重做命令
    const broadcastUndoRedoCommand = (type, data) => {
      
        if (!wsProvider.wsconnected) {
            console.warn('WebSocket未连接，无法广播撤销/重做命令');
            return false;
        }

        try {
            console.log('广播撤销/重做命令:', type, data);

            // 使用awareness机制发送命令
            wsProvider.awareness.setLocalStateField('canvasCommand', {
                type: type,
                state: data.state,
                stackInfo: data.stackInfo,
                userId: userId,
                timestamp: Date.now()
            });

            // 短暂延迟后清除通知，避免状态污染和死循环
            setTimeout(() => {
                wsProvider.awareness.setLocalStateField('canvasCommand', null);
            }, 500);

            return true;
        } catch (error) {
            console.error('广播撤销/重做命令失败:', error);
            return false;
        }
    };

   
    // 从共享对象更新画布
    function updateCanvasFromSharedObjects() {
        try {
            if (isUpdatingFromRemote || !canvas || !canvas.getContext()) {
                return;
            }

            isUpdatingFromRemote = true;

            // 创建一个Map来存储远程对象的所有可能ID和它们的完整数据
            const remoteObjectMap = new Map();

            // 首先收集所有远程对象的信息
            sharedObjects.forEach((serializedData, key) => {
                try {
                    const data = JSON.parse(serializedData);
                    if (data.objData && data.objData.id) {
                        remoteObjectMap.set(data.objData.id, data.objData);
                    }
                } catch (e) {
                    console.error('解析远程对象数据失败:', e);
                }
            });

            // 获取当前画布上的所有对象
            const localObjects = canvas.getObjects();
            const localObjectMap = new Map();
            localObjects.forEach((obj) => {
                if (obj.id && obj.type !== 'cursor') {
                    localObjectMap.set(obj.id, obj);
                }
            });

            

            // 存储创建对象的Promise
            const objectPromises = [];

            // 添加或更新远程对象
            for (const [id, objData] of remoteObjectMap) {
                const existingObj = findObjectById(canvas, id);

                if (existingObj) {
                    // 更新现有对象
                    try {
                        updateFabricObject(existingObj, objData);
                        if (existingObj.canvas) {
                            existingObj.setCoords();
                        }
                    } catch (error) {
                        console.error('更新对象失败:', error);
                        // 如果更新失败，尝试重新创建对象
                        canvas.remove(existingObj);
                        const newObjPromise = createAndAddObject(id, objData);
                        if (newObjPromise) {
                            objectPromises.push(newObjPromise);
                        }
                    }
                } else {
                    // 创建新对象
                    const newObjPromise = createAndAddObject(id, objData);
                    if (newObjPromise) {
                        objectPromises.push(newObjPromise);
                    }
                }
            }

            // 等待所有对象加载完成
            Promise.all(objectPromises)
                .then(() => {
                    // 更新所有对象的坐标
                    canvas.getObjects().forEach((obj) => {
                        if (obj && obj.canvas && typeof obj.setCoords === 'function') {
                            obj.setCoords();
                        }
                    });

                    // 延迟一帧再渲染，确保一切都准备好了
                    requestAnimationFrame(() => {
                        if (canvas && canvas.getContext()) {
                            canvas.requestRenderAll();
                        }
                    });
                })
                .catch((error) => {
                    console.error('对象加载过程中出错:', error);
                })
                .finally(() => {
                    setTimeout(() => {
                        isUpdatingFromRemote = false;
                    }, 100);
                });
        } catch (error) {
            console.error('更新画布内容时出错:', error);
            isUpdatingFromRemote = false;
        }
    }
    // 添加新的辅助函数来创建和添加对象
    function createAndAddObject(id, objData) {
        try {
            return Promise.resolve(createFabricObject(objData)).then((newObj) => {
                if (newObj) {
                    if (typeof newObj.then === 'function') {
                        return newObj.then((asyncObj) => {
                            if (asyncObj) {
                                asyncObj.id = id;
                                if (canvas && canvas.getContext()) {
                                    canvas.add(asyncObj);
                                    return asyncObj;
                                }
                            }
                            return null;
                        });
                    } else {
                        newObj.id = id;
                        if (canvas && canvas.getContext()) {
                            canvas.add(newObj);
                            return newObj;
                        }
                    }
                }
                return null;
            });
        } catch (error) {
            console.error('创建对象失败:', error);
            return null;
        }
    }


    // 更新updateFabricObject函数
    function updateFabricObject(fabricObj, objData) {
        try {
            if (!fabricObj || !fabricObj.canvas) {
                throw new Error('Invalid fabric object or canvas');
            }

            // 更新对象属性
            fabricObj.set(objData);

            // 更新坐标
            if (typeof fabricObj.setCoords === 'function') {
                fabricObj.setCoords();
            }
        } catch (error) {
            console.error('更新对象属性时出错:', error);
            throw error;
        }
    }

    // 监听共享对象变化
    sharedObjects.observe((event) => {
        // console.log('共享对象变化:', event);
        if (undoRedoManagerRef?.current?.isRestoringState || undoRedoManagerRef?.current?.isUndoRedoOperation) {
            return;
        }
        if (!isUpdatingFromRemote) {
            updateCanvasFromSharedObjects();
        }
    });

    // 监听canvas对象添加事件
    canvas.on('object:added', (e) => {
        // 如果是在恢复状态或执行撤销/重做操作，直接返回
        if (undoRedoManagerRef?.current?.isRestoringState || undoRedoManagerRef?.current?.isUndoRedoOperation) {
            return;
        }
        
       
        if (e.target && !isUpdatingFromRemote) {
            const obj = e.target;

            // 忽略光标对象
            if (obj.type === 'cursor') {
                return;
            }

            try {
             
                // 确保对象有唯一ID
                if (!obj.id) {
                    obj.id = `obj_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
                }

                // 如果是组合对象，单独处理每个子对象
                if (obj.type === 'activeSelection') {
                    // 1. 获取所有子对象
                    const objects = obj.getObjects();
                    
                    // 2. 记录组合属性和每个子对象的相对位置
                    const groupProps = {
                        left: obj.left,
                        top: obj.top,
                        angle: obj.angle,
                        scaleX: obj.scaleX,
                        scaleY: obj.scaleY
                    };

                    // 记录每个子对象相对于组合的位置
                    const relativePositions = objects.map(childObj => ({
                        id: childObj.id,
                        left: childObj.left - obj.left,  // 相对于组合的x偏移
                        top: childObj.top - obj.top,      // 相对于组合的y偏移
                        angle: childObj.angle,
                        scaleX: childObj.scaleX,
                        scaleY: childObj.scaleY
                    }));

                    // 3. 临时解散组合
                    canvas.discardActiveObject();

                    // 4. 同步每个子对象
                    objects.forEach((childObj, index) => {
                        if (!childObj.id) {
                            childObj.id = `obj_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
                        }
                        // 更新子对象的位置
                        const relativePos = relativePositions[index];
                        childObj.set({
                            left: groupProps.left + relativePos.left,
                            top: groupProps.top + relativePos.top,
                            angle: relativePos.angle,
                            scaleX: relativePos.scaleX,
                            scaleY: relativePos.scaleY
                        });
                        childObj.setCoords();
                        const childData = childObj.toJSON(['id']);
                        const serializedObj = JSON.stringify({
                            id: childObj.id,
                            type: childObj.type || 'unknown',
                            objData: childData,
                            timestamp: Date.now(),
                            userId: userId
                        });
                        sharedObjects.set(childObj.id, serializedObj);
                    });

                    // 5. 重新创建组合
                    const newSelection = new fabric.ActiveSelection(objects, {
                        canvas: canvas
                    });

                    // 6. 恢复组合属性
                    newSelection.set(groupProps);
                    canvas.setActiveObject(newSelection);
                    canvas.requestRenderAll();

                    // 发送修改通知
                    wsProvider.awareness.setLocalStateField('modifyNotification', {
                        objectIds: objects.map(obj => obj.id),
                        groupProps: groupProps,
                        relativePositions: relativePositions,
                        timestamp: Date.now(),
                        userId: userId
                    });
                } else {
                    // 单个对象直接处理
                    const objData = obj.toJSON(['id']);
                    const serializedObj = JSON.stringify({
                        id: obj.id,
                        type: obj.type || 'unknown',
                        objData: objData,
                        timestamp: Date.now(),
                        userId: userId
                    });
                    sharedObjects.set(obj.id, serializedObj);
                }
            } catch (error) {
                console.error('处理对象添加事件时出错:', error);
            }
        }
    });

    // 修改 object:modified 事件处理
    canvas.on('object:modified', (e) => {
        // 如果是在恢复状态或执行撤销/重做操作，直接返回
        if (undoRedoManagerRef?.current?.isRestoringState || undoRedoManagerRef?.current?.isUndoRedoOperation) {
            return;
        }
       

        if (e.target && !isUpdatingFromRemote) {
            const obj = e.target;
            // console.log('同步对象修改:', obj.type, obj.fill, obj.id);
            // console.log('object:modified++++++++++++++++++', obj, obj.type);
            // 忽略光标对象
            if (obj.type === 'cursor') {
                return;
            }
           
            try {
                // 如果是组合对象，只遍历并同步各个子对象
                if (obj.type === 'activeSelection') {
                    // 1. 获取所有子对象
                    const objects = obj.getObjects();
                    
                    // 2. 记录组合属性和每个子对象的相对位置
                    const groupProps = {
                        left: obj.left,
                        top: obj.top,
                        angle: obj.angle,
                        scaleX: obj.scaleX,
                        scaleY: obj.scaleY
                    };

                    // 记录每个子对象相对于组合的位置
                    const relativePositions = objects.map(childObj => ({
                        id: childObj.id,
                        left: childObj.left - obj.left,  // 相对于组合的x偏移
                        top: childObj.top - obj.top,      // 相对于组合的y偏移
                        angle: childObj.angle,
                        scaleX: childObj.scaleX,
                        scaleY: childObj.scaleY
                    }));

                    // 3. 临时解散组合
                
                    // 4. 同步每个子对象
                    objects.forEach((childObj, index) => {
                        if (!childObj.id) {
                            childObj.id = `obj_${Date.now()}_${Math.floor(Math.random() * 1000)}`;
                        }
                        // 更新子对象的位置
                        const relativePos = relativePositions[index];
                        childObj.set({
                            left: groupProps.left + relativePos.left,
                            top: groupProps.top + relativePos.top,
                            angle: relativePos.angle,
                            scaleX: relativePos.scaleX,
                            scaleY: relativePos.scaleY
                        });
                        
                        const childData = childObj.toJSON(['id']);
                        const serializedObj = JSON.stringify({
                            id: childObj.id,
                            type: childObj.type || 'unknown',
                            objData: childData,
                            timestamp: Date.now(),
                            userId: userId
                        });
                        sharedObjects.set(childObj.id, serializedObj);
                        childObj.setCoords();
                    });

                    // 5. 重新创建组合
                  

                    // 6. 恢复组合属性
                    obj.set(groupProps);
                    obj.setCoords();
                    canvas.requestRenderAll();


                } else {
                    // 单个对象直接同步 - 不修改属性
                    const objData = obj.toJSON(['id']);
                    const serializedObj = JSON.stringify({
                        id: obj.id || `obj_${Date.now()}`,
                        type: obj.type || 'unknown',
                        objData: objData,
                        timestamp: Date.now(),
                        userId: userId
                    });
                    sharedObjects.set(obj.id, serializedObj);
                }
            } catch (err) {
                console.error('处理对象失败:', err);
            }
        }
    });
    // 添加删除按钮点击事件处理
    const handleDelete = (id) => {
      
        if (id) {
            sharedObjects.delete(id);
            wsProvider.awareness.setLocalStateField('deleteNotification', {
                objectId: id,
                timestamp: Date.now(),
                userId: userId
            });
        }
        
        // 短暂延迟后清除通知
        setTimeout(() => {
            wsProvider.awareness.setLocalStateField('deleteNotification', null);
        }, 500);
    };

    // 监听canvas对象删除事件
    canvas.on('object:removed', (e) => {
        // 如果是在恢复状态或执行撤销/重做操作，直接返回
        if (undoRedoManagerRef?.current?.isRestoringState || undoRedoManagerRef?.current?.isUndoRedoOperation) {
            return;
        }
        

        if (!isUpdatingFromRemote) {
            const obj = e.target;
            if (!obj) return;

            // 忽略光标对象
            if (obj.type === 'cursor') {
                return;
            }
            
            // 处理组合对象
            if (obj.type === 'activeSelection') {
                // 删除组合中的所有子对象
                obj.forEachObject((childObj) => {
                    if (childObj.id) {
                        sharedObjects.delete(childObj.id);
                        // 发送删除通知
                        wsProvider.awareness.setLocalStateField('deleteNotification', {
                            objectId: childObj.id,
                            timestamp: Date.now(),
                            userId: userId
                        });
                    }
                });
            } else if (obj.id) {
                // 处理单个对象
                sharedObjects.delete(obj.id);
                wsProvider.awareness.setLocalStateField('deleteNotification', {
                    objectId: obj.id,
                    timestamp: Date.now(),
                    userId: userId
                });
            }
            
            // 短暂延迟后清除通知
            setTimeout(() => {
                wsProvider.awareness.setLocalStateField('deleteNotification', null);
            }, 500);
        }
    });

    // 处理用户光标位置更新
    awareness.on('change', () => {
        const states = awareness.getStates();
        const users = [];
        // 检查是否有删除通知
        for (const [clientId, state] of states.entries()) {
            if (state.deleteNotification && clientId !== wsProvider.awareness.clientID) {
                const deleteInfo = state.deleteNotification;

                // 处理删除
                isUpdatingFromRemote = true;
                const objectToDelete = findObjectById(canvas, deleteInfo.objectId);
                if (objectToDelete) {
                    canvas.remove(objectToDelete);
                    canvas.requestRenderAll();
                }

                // 从共享对象中移除
                if (sharedObjects.has(deleteInfo.objectId)) {
                    sharedObjects.delete(deleteInfo.objectId);
                }

                setTimeout(() => {
                    isUpdatingFromRemote = false;
                }, 100);
            }

            if (state) {
                // 检查 canvasCommand
                if (state.canvasCommand) {
                  
                    if (clientId !== wsProvider.awareness.clientID) {
                        if (state.canvasCommand.type === 'command:undo' || 
                            state.canvasCommand.type === 'command:redo') {
                          
                         
                            // 检查是否是重复命令
                            if (lastProcessedCommand && 
                                lastProcessedCommand.timestamp === state.canvasCommand.timestamp &&
                                lastProcessedCommand.type === state.canvasCommand.type) {
                                console.log('忽略重复命令');
                                return;
                            }
                            
                            // 记录最后处理的命令，确保包含时间戳
                            lastProcessedCommand = {
                                ...state.canvasCommand,
                                timestamp: state.canvasCommand.timestamp || Date.now()
                            };
                            
                            console.log('收到远程画布命令:', state.canvasCommand);
                            document.dispatchEvent(new CustomEvent('remote-canvas-command', {
                                detail: state.canvasCommand
                            }));
                        }
                    }
                }
            }
        }

        // 处理清空画布消息
        let hasClearCanvasEvent = false;
        let latestClearCanvasTimestamp = 0;
        let latestClearCanvasClientId = null;

        // 首先检查是否有任何清空画布消息，找出最新的一个
        for (const [clientId, state] of states.entries()) {
            // 忽略自己的消息
            if (state.clearCanvas && clientId !== wsProvider.awareness.clientID) {
                hasClearCanvasEvent = true;

                // 找出时间戳最新的清空事件
                if (state.clearCanvas.timestamp > latestClearCanvasTimestamp) {
                    latestClearCanvasTimestamp = state.clearCanvas.timestamp;
                    latestClearCanvasClientId = clientId;
                }
            }
        }

        // 如果找到了清空画布消息，并且时间戳比上一次处理的更新，则处理它
        if (hasClearCanvasEvent && latestClearCanvasTimestamp > lastClearCanvasTime) {
            console.log('收到新的清空画布消息，时间戳:', latestClearCanvasTimestamp);

            // 更新最后处理的时间戳
            lastClearCanvasTime = latestClearCanvasTimestamp;

            isUpdatingFromRemote = true;

            // 清空本地画布
            canvas.clear();
            canvas.setBackgroundColor('#ffffff', canvas.requestRenderAll.bind(canvas));

            // 恢复标志
            setTimeout(() => {
                isUpdatingFromRemote = false;
            }, 100);

            // 触发事件
            document.dispatchEvent(new CustomEvent('canvas-cleared-remotely'));
        }

        // 获取 localStorage 中的 customColor
        const customColor = localStorage.getItem('customColor');

        // 收集所有在线用户，包括自己
        states.forEach((state, clientId) => {
            if (state.user) {
                users.push({
                    id: state.user.userId,
                    name: state.user.name,
                    // 如果是当前用户，使用 customColor，否则使用用户自己的颜色
                    color: clientId === awareness.clientID ?
                        customColor || state.user.color : state.user.color,
                    cursor: state.cursor,
                    isCurrentUser: clientId === awareness.clientID
                });
            }
        });

        // 触发用户列表更新事件
        const userListEvent = new CustomEvent('userListUpdated', { detail: { users } });
        document.dispatchEvent(userListEvent);

        // 更新画布上的光标
        updateCursors(canvas, states);
    });

    // 设置30秒定期广播自己的状态，确保其他客户端能看到
    const awarenessInterval = setInterval(() => {
        if (wsProvider.wsconnected) {
            // 获取 localStorage 中的 customColor
            const customColor = localStorage.getItem('customColor');

            // 重新设置用户信息，触发广播
            awareness.setLocalStateField('user', {
                name: userName,
                color: customColor || getRandomColor(),
                userId: userId,
                lastUpdate: Date.now()
            });
            console.log('广播awareness状态...');
        }
    }, 30000);

    // 更新用户光标位置
    canvas.on('mouse:move', (e) => {
        const pointer = canvas.getPointer(e.e);
        // 设置标志，表示这是光标移动
        e.e._isCursorMove = true;
        awareness.setLocalStateField('cursor', {
            x: pointer.x,
            y: pointer.y
        });
    });

    // 返回需要的接口
    const result = {
        ydoc,
        wsProvider,
        awareness,
        userId,
        checkConnection,
        broadcastClearCanvas,
        broadcastUndoRedoCommand,
        sharedObjects,
        handleDelete,  // 添加删除处理函数到返回接口
        // 添加清理函数引用
        cleanup: () => {
            // 清除定时器
            if (awarenessInterval) {
                clearInterval(awarenessInterval);
            }
        }
    };

    return result;
}

// 根据ID查找画布对象
function findObjectById(canvas, id) {
    return canvas.getObjects().find((obj) => obj.id === id);
}

// 创建Fabric对象
function createFabricObject(objData) {
    // 我们需要确保fabric已经加载
    if (typeof window.fabric === 'undefined') {
        console.error('Fabric不可用');
        return null;
    }

    const { fabric } = window;
    const { type } = objData;
    let fabricObj;

    try {
        // 根据类型创建对应的Fabric对象
        switch (type) {
            case 'rect':
                fabricObj = new fabric.Rect(objData);
                break;
            case 'circle':
                fabricObj = new fabric.Circle(objData);
                break;
            case 'ellipse':
                fabricObj = new fabric.Ellipse(objData);
                break;
            case 'triangle':
                fabricObj = new fabric.Triangle(objData);
                break;
            case 'path':
                fabricObj = new fabric.Path(objData.path, objData);
                break;
            case 'text':
            case 'i-text':
                fabricObj = new fabric.IText(objData.text || '文本', objData);
                break;
            case 'image':
                // 处理图片对象
                if (objData.src) {
                    return new Promise((resolve) => {
                        fabric.Image.fromURL(
                            objData.src,
                            (img) => {
                                if (!img) {
                                    console.error('无法加载图片:', objData.src);
                                    resolve(null);
                                    return;
                                }

                                // 应用所有属性
                                img.set(objData);

                                // 确保ID被保留
                                if (objData.id) {
                                    img.id = objData.id;
                                }

                                console.log('图片对象创建成功');
                                resolve(img);
                            }, { crossOrigin: 'anonymous' }
                        );
                    });
                } else {
                    console.error('图片缺少src属性');
                    return null;
                }
            case 'line':
                fabricObj = new fabric.Line(
                    [objData.x1 || 0, objData.y1 || 0, objData.x2 || 100, objData.y2 || 100],
                    objData
                );
                break;
            case 'polygon':
                fabricObj = new fabric.Polygon(objData.points || [], objData);
                break;
            case 'polyline':
                fabricObj = new fabric.Polyline(objData.points || [], objData);
                break;
            case 'group':
                // 处理群组
                if (objData.objects && Array.isArray(objData.objects)) {
                    const groupObjects = objData.objects
                        .map((obj) => createFabricObject(obj))
                        .filter((obj) => obj);
                    if (groupObjects.length > 0) {
                        fabricObj = new fabric.Group(groupObjects, objData);
                        console.log('创建群组对象:', groupObjects.length, '个子对象');
                    } else {
                        console.warn('群组没有有效的子对象');
                        return null;
                    }
                } else {
                    console.warn('群组数据缺少objects数组');
                    return null;
                }
                break;
            default:
                console.warn(`不支持的对象类型: ${type}`);
                return null;
        }

        return fabricObj;
    } catch (error) {
        console.error(`创建对象类型 ${type} 时出错:`, error);
        return null;
    }
}

// 更新画布上的用户光标
function updateCursors(canvas, states) {
    // 确保fabric已经加载
    if (typeof window.fabric === 'undefined') {
        console.error('Fabric不可用');
        return;
    }

    // 确保画布存在且已初始化
    if (!canvas || !canvas.getContext()) {
        console.warn('Canvas未初始化或已销毁，跳过光标更新');
        return;
    }

    const { fabric } = window;

    try {
        // 移除现有光标
        const cursors = canvas.getObjects().filter((obj) => obj.type === 'cursor');
        cursors.forEach((c) => canvas.remove(c));

        // 添加新光标
        states.forEach((state, clientId) => {
            if (state.user && state.cursor && clientId !== states.clientID) {
                drawCursor(
                    canvas,
                    state.cursor.x,
                    state.cursor.y,
                    state.user.color,
                    state.user.name,
                    fabric
                );
            }
        });

        canvas.requestRenderAll();
    } catch (error) {
        console.error('更新光标时出错:', error);
    }
}

// 绘制光标
function drawCursor(canvas, x, y, color, name, fabric) {
    // 安全检查
    if (!canvas || !fabric) {
        return;
    }

    try {
        // 获取 localStorage 中的 customColor，如果没有则使用传入的颜色
        const customColor = localStorage.getItem('customColor') || color || '#ff0000';

        // 在用户名前添加空格，使其与鼠标位置有一定距离
        const label = new fabric.Text('    ' + (name || 'User'), {
            left: x,
            top: y,
            fontSize: 12,
            fill: customColor,
            selectable: false,
            evented: false,
            type: 'cursor'
        });

        canvas.add(label);
    } catch (error) {
        console.error('绘制光标时出错:', error);
    }
}

// 生成随机颜色
function getRandomColor() {
    const colors = [
        '#FF5733',
        '#33FF57',
        '#3357FF',
        '#F3FF33',
        '#33FFF3',
        '#F333FF',
        '#FF3333',
        '#33FF33',
        '#3333FF',
        '#FFAA33',
        '#33FFAA',
        '#AA33FF'
    ];
    return colors[Math.floor(Math.random() * colors.length)];
}